#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymongo;
import re
from  config import *

# browser=webdriver.PhantomJS(service_args=SERVICE_ARGS);
client = pymongo.MongoClient(MONGO_URL);
db = client["xiecheng"];
TABLE="holtel"
import pandas as pd
import numpy as np
import matplotlib.pyplot as plot
#指定默认字体
plot.rcParams['font.sans-serif'] = ['SimHei']
plot.rcParams['font.family']='sans-serif'
def get_data():
    queryArgs = {}
    projectionFields = {'_id': False}  # 用字典指定
    result = db[TABLE].find(queryArgs,projectionFields)
    return result








def main():
    data=pd.DataFrame(list(get_data()))

    data.pop("url")

    data_in=pd.DataFrame(data,columns=["score","price","com_count","name"])

    # print(data_in.head())
    data_in["com_count"]=data_in["com_count"].astype(np.int32)
    data_in["score"]=data_in["score"].astype(np.float)
    data_in["price"]=data_in["price"].astype(np.int32)
    data_in=data_in.sort_values(by="com_count",ascending=False)
    print(data_in.describe())
    print(data_in.head())
    data_in=data_in[data_in.com_count>628]
    print(data_in.describe())
    data_in = data_in.sort_values(by="score", ascending=False)
    data_in=data_in[data_in.price<250]
    data_in=data_in.head(20)
    print(data_in.head(20))
    data_in["name"]=data_in["name"].apply(title)
    print(data_in.index)
    # data_in["address"]=data.loc[data_in.index]
    data_in["address"]=data.iloc[data_in.index]["address"]
    data_in["address"]=data_in["address"].apply(get_address)
    data_save=pd.DataFrame(data_in,columns=["name","address"])
    data_save.to_csv("good_hotel.csv",encoding="utf-8")
    print(data_save)


def get_address(address):
    result=re.compile("】(.*?)地图").search(address).group(1)
    return "杭州市 "+result


def show(data_in):
    plot.style.use("seaborn-bright")
    bar_width = 0.3
    plot.figure(figsize=(16, 6))
    plot.title("性价比最高的10个酒店评分")
    plot.xticks(fontsize=7)
    plot.ylabel("评分")
    p2 = plot.bar(data_in["name"], data_in["score"], bar_width)
    plot.xticks(Rotation=45)
    plot.savefig("hotel_score.png")
    plot.show()


def title(str):
    try:
        start=str.index("(")
        res= str[:start]
    except:
        print("error")
        res=str

    return res


if __name__ == '__main__':
    main()
    # print("a".join("bcdef"))